package com.czk.gulimall.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 两任务组合，都要完成
 *
 * @Author:ChenZhangKun
 * @Date: 2022/2/10 15:38
 */
public class CompletableFutureTest3 {
    private static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 第一个任务
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务一启动了");
            int i = 10 / 2;
            System.out.println("任务一结束了");
            return i;
        }, executor);
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务二启动了");
            int i = 10 / 2;
            System.out.println("任务二结束了");
            return i;
        }, executor);

        // 不能感知前两个结果
        future1.runAfterBothAsync(future2, () -> {
            System.out.println("任务3开始");
        });
        // 可以感知前两个的任务
        future1.thenAcceptBothAsync(future2, (f1, f2) -> {
            System.out.println(f1 + f2);
        }, executor);


        // 感知前两个任务结果，并有返回值
        CompletableFuture<Integer> integerCompletableFuture = future1.thenCombineAsync(future2, (f1, f2) -> {
            System.out.println(f1 + f2);
            return f1 * f2;
        }, executor);

        System.out.println(integerCompletableFuture.get());
    }
}
